<template>
  <div>
    <basic-page-vxe
      ref="basePage"
      :columns="basicData.columns"
      :search-form="basicData.searchForm"
      :search-handle="basicData.searchHandle"
      list-api="querySysUrl"
      del-api="deleteSysUrl"
      export-api="exportSysUrl"
      :export-name="$route.meta.title"
    />
    <!--    新增、删除 -->
    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="90px" style="width: 100%">
        <el-form-item label="URL" prop="url">
          <el-input v-model="temp.url" placeholder="请输入" minlength="3" maxlength="64" clearable />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="temp.description" type="textarea" placeholder="请输入" minlength="3" maxlength="64" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="授权角色" :visible.sync="showAth" width="500px">
      <div>
        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;" />
        <el-checkbox-group v-model="checkedRoles" @change="handleCheckedRolesChange">
          <el-checkbox v-for="role in roleIdOptions" :key="role.value" :label="role.value">{{ role.name }}</el-checkbox>
        </el-checkbox-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAth = false">
          取消
        </el-button>
        <el-button type="primary" @click="checkAth">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addSysUrl, updateSysUrl, queryRoleName, queryRoleIdByUrlId, authorizeRoleToUrl } from '@/api/authority'
export default {
  name: '',
  components: {
  },
  directives: {},
  filters: {},
  data() {
    return {
      basicData: {
        columns: [
          { config: { title: 'URL', field: 'url' }, type: 'copy' },
          { config: { title: '描述', field: 'description' }},
          { config: { title: '创建日期', width: '160', field: 'createTime' }, type: 'time' },
          { config: { title: '操作', field: 'opt', width: '260' }, type: 'render',
            render: (h, scope) => {
              return (
                <div>
                  <el-button plain size='mini' type='primary' v-permission="'update'" onClick={() => this.handleUpdate(scope.row)}><i class='el-icon-edit'></i> 编辑</el-button>
                  <el-button plain size='mini' type='warning' v-permission="'authorize'" onClick={() => this.showAthDialog(scope.row)}><i class='el-icon-s-check'></i> 授权</el-button>
                  <el-button plain size='mini' type='danger' v-permission="'delete'" onClick={() => this.$refs.basePage.handleDelete(scope.row)}><i class='el-icon-delete'></i> 删除</el-button>
                </div>
              )
            }
          }
        ],
        searchData: {
          url: null,
          currentPage: 1,
          pageSize: 10
        },
        searchForm: [
          { type: 'Input', label: 'URl', prop: 'url', width: '80px' }
        ],
        searchHandle: [
          { label: '新增', type: 'success', icon: 'el-icon-plus', permission: 'add', handle: () => { this.handleCreate() } }
        ]

      },
      typ: [],
      detail: {},
      roleIdOptions: [],
      orgIdOptions: [],
      orgName: '',
      temp: {
        id: undefined,
        status: 1,
        prefix: '86'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        url: [{ required: true, message: '请输入URL！', trigger: 'blur' }]
      },
      downloadLoading: false,
      showAth: false,
      checkAll: false,
      checkedRoles: [],
      isIndeterminate: true
    }
  },
  computed: {},
  created() {
    this.getType()
  },
  mounted() {
  },
  methods: {
    // 业务逻辑
    getType() {
      queryRoleName().then(response => {
        this.roleIdOptions = response.data
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        status: 1,
        prefix: '86'
      }
    },
    handleCreate() {
      this.resetTemp()
      this.orgName = ''
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addSysUrl(this.temp).then(response => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
            this.handleReset()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.orgName = this.temp.orgIdCn
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateSysUrl(tempData).then(response => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 2000
            })
            this.handleReset()
          })
        }
      })
    },
    handleReset() {
      this.$refs.basePage.getList()
    },
    showAthDialog(row) {
      this.showAth = true
      this.urlRow = Object.assign({}, row) // copy obj
      queryRoleIdByUrlId({ urlId: row.id }).then(response => {
        this.checkedRoles = response.data
        const checkedCount = response.data.length
        this.checkAll = checkedCount === this.roleIdOptions.length
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.roleIdOptions.length
      })
    },
    handleCheckAllChange(val) {
      this.checkedRoles = val ? this.roleIdOptions.map(item => { return item.value }) : []
      this.isIndeterminate = false
    },
    handleCheckedRolesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.roleIdOptions.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.roleIdOptions.length
    },
    checkAth() {
      const formData = new FormData()
      for (const k of this.checkedRoles) {
        formData.append('roleId', k)
      }
      formData.append('urlId', this.urlRow.id)
      authorizeRoleToUrl(formData).then(response => {
        if (response.message === 'success') {
          this.$notify({
            title: '成功',
            message: '授权成功',
            type: 'success',
            duration: 2000
          })
          this.showAth = false
        }
      })
    }
  }
}
</script>

<style scoped>
.warning{
  text-align: center;
  font-size: 20px;
}
.el-icon-info{
  font-size: 30px;
  color: orange;
}
</style>
